package com.ch4;

import lombok.extern.slf4j.Slf4j;

/**
 * @author woldier
 * @version 1.0
 * @description synchronized 面对对象
 * @date 2023/4/19 11:03
 **/
@Slf4j(topic = "c.Thread")
public class Demo02 {
    public static void main(String[] args) throws InterruptedException {
        //t1();
        t2();
    }

    public static void t1() throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.inc();
            }
        }, "减法器");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.dec();
            }
        }, "减法器");


        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(room.getCount());
    }

    public static void t2() throws InterruptedException {
        Room2 room = new Room2();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.inc();
            }
        }, "减法器");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.dec();
            }
        }, "减法器");


        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(room.getCount());
    }

    static class Room {
        private int count = 5000;

        /**
         * description 加锁的inc
         *
         * @return void
         * @author: woldier
         * @date: 2023/4/19 11:07
         */
        public void inc() {
            synchronized (this) { //对当前类的实体对象加锁
                count++;
            }
        }

        /**
         * description 加锁的dec
         *
         * @return void
         * @author: woldier
         * @date: 2023/4/19 11:07
         */
        public void dec() {
            synchronized (this) {
                count--;
            }
        }

        public int getCount() {
            synchronized (this) {
                return count;
            }
        }
    }

    static class Room2 {
        private int count = 5000;

        /**
         * description 加锁的inc 加在方法上 锁住的this对象
         *
         * @return void
         * @author: woldier
         * @date: 2023/4/19 11:07
         */
        public synchronized void inc() {
            count++;
        }

        /**
         * description 加锁的dec 加在方法上锁住的this对象
         *
         * @return void
         * @author: woldier
         * @date: 2023/4/19 11:07
         */
        public synchronized void dec() {
            count--;
        }

        public int getCount() {
            return count;
        }
    }

}


